<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>闭包</title>
</head>
<body>
<ul>
  <li><p>让这些变量的值始终保持在内存中。</p></li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>
<script type="text/javascript">
  var oLi = document.querySelectorAll("li");

  /*
  for(var i=0;i<oLi.length;i++){
    oLi[i].onclick=function (){
      alert(i)//一直弹出5,变量没有保存
    }
  }
  */

  for(var i=0;i<oLi.length;i++){
    oLi[i].onclick=closure(i)
  }
  function closure(i) {
    var onclick=function(){
      alert(i);
    };
    return onclick;
  }
</script>
</body>
</html>
